package com.baor.handler;

import com.baor.base.config.TokenService;
import com.baor.base.domain.UserVO;
import com.baor.base.util.RedisUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationHandler implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        String token = request.getHeader("token");
        if(token == null){
            return false;
        }
        // 验证token
        UserVO userInfo = this.tokenService.getUserInfo(token);
        if(userInfo == null){
            return false;
        }
        Object value = this.redisUtil.getValue("loginUser:" + userInfo.getUserId());
        if(value != null && value.equals(token)){
            return true;
        }else{
            return false;
        }
    }
}
